const express = require('express')
// 加載配置信息
const { configFile:{node: {port,host}} } = require('./config/readYamlFile')
// 打印控制信息
const Log = require('./config/log')
const Token = require('./authMiddle/index');
const accessLogStream = require('./Logger')
const commonFunction = require('./config/commonFunction');
//用于post请求解析req.body消息体
const bodyParser = require('body-parser')
const static = require('express-static');
const path = require('path');
const morgan = require('morgan')
const helmet = require('helmet')
const cors = require('cors');
const app = express()


app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(helmet()) // 防止xss攻击s
app.use(cors()) // 跨域
app.use('/static',static(path.join(__dirname, 'public')));// 访问 http:localhost:9090/01.jpg
app.use(morgan('combined',{stream: accessLogStream})) // 日志接口
// 路由jwt设置
app.use(function (req,res,next) {
    if(req.path === '/login' || req.path === '/register') {
        next();
    }else {
    // 1. 获取ajax中的header
        const result = req.headers.authorization;
        if(!result || result === 'null') {
            res.send(commonFunction.TokenFail())
            return
        }
        try {
            const decrypt = Token.decrypt(result);
            console.log(decrypt)
            next();
        }catch (e) {
            res.send(commonFunction.TokenFail('token验证失败或过期'))
        }
    }
})

//路由
app.use('/',require('./router/initRouter'))
app.use('/user',require('./router/index'))


app.listen(port, host, function (err) {
    if(err) {
       Log.LogBlackBright('The server is down')
        throw err;
    }
    Log.LogCyanBright('The server is up')
    Log.LogYellowBright(`listening to port is ${port},Please visit the http://${host}:${port}`)
});

